﻿using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.XJ;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.XJ;
using Nop.Web.Framework.Security;
using Nop.Web.Models.Home;
using Nop.Web.Models.XJ;
using Senparc.Weixin;
using Senparc.Weixin.Entities.TemplateMessage;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.WxOpen.AdvancedAPIs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace Nop.Web.Controllers
{
	public class MaintenanceController : Controller
	{
		#region Fields
		private readonly static string appId = "wx254193524213940e";
		private readonly static string appSecret = "c020d4fcaceaef04d03194bcf408ba51";
		private readonly IDepartmentService _departmentService;
		private readonly ICustomerService _customerService;
		private readonly IFilesService _filesService;
		private readonly IPictureService _pictureService;
		private readonly IMessageService _messageService;
		private readonly ILogger _logger;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJPlaceService _xjPlaceService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJEquipmentStockOutService _xJEquipmentStockOutService;
		private readonly IXJEquipmentStockOutDetailService _xJEquipmentStockOutDetailService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJInspectionPlanService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceDetailService _xJMaintenanceDetailService;
		private readonly IXJMaintenanceCustomersService _xJMaintenanceCustomersService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		private readonly IXJMaintenanceScheduleService _xJMaintenanceScheduleService;
		#endregion

		#region Ctor
		public MaintenanceController(
			IDepartmentService departmentService,
			ICustomerService customerService,
			IFilesService filesService,
			IPictureService pictureService,
			IMessageService messageService,
			ILogger logger,
			IGenericAttributeService genericAttributeService,
			IXJPlaceService xjPlaceService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJEquipmentStockOutService xJEquipmentStockOutService,
			IXJEquipmentStockOutDetailService xJEquipmentStockOutDetailService,
			IXJInspectionService xJInspectionService,
			IXJInspectionPlanService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceDetailService xJMaintenanceDetailService,
			IXJMaintenanceCustomersService xJMaintenanceCustomersService,
			IXJMaintenanceCommentService xJMaintenanceCommentService,
			IXJMaintenanceScheduleService xJMaintenanceScheduleService)
		{
			this._departmentService = departmentService;
			this._customerService = customerService;
			this._filesService = filesService;
			this._pictureService = pictureService;
			this._messageService = messageService;
			this._logger = logger;
			this._genericAttributeService = genericAttributeService;
			this._xjPlaceService = xjPlaceService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJEquipmentStockOutService = xJEquipmentStockOutService;
			this._xJEquipmentStockOutDetailService = xJEquipmentStockOutDetailService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceDetailService = xJMaintenanceDetailService;
			this._xJMaintenanceCustomersService = xJMaintenanceCustomersService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
			this._xJMaintenanceScheduleService = xJMaintenanceScheduleService;
		}
		#endregion

		#region Utilities

		/// <summary>
		/// 工时
		/// </summary>
		/// <param name="minutes"></param>
		/// <returns></returns>
		[NonAction]
		private string GetHoursString(int minutes)
		{
			if (minutes <= 0)
				return "";

			if (minutes < 60)
				return string.Format("{0}分", minutes);

			int h = minutes / 60; // 计算小时数
			int m = minutes % 60; // 计算剩余的分钟数
			return string.Format("{0}时{1}", h, m > 0 ? m + "分" : "");
		}
		#endregion

		[HttpPost]
		[UserValidator]
		public JsonResult List(Customer customer, string sNo = "", string comment = "", int state = 0, int pageIndex = 0, int pageSize = 10)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var alls = _xJMaintenanceService.GetMaintenances(
				customer: customer,
				sNo: sNo,
				comment: comment,
				state: state,
				pageIndex: pageIndex,
				pageSize: pageSize);
			return Json(new
			{
				result = true,
				model = alls.Select(x =>
				{
					var item = new ListItemModel
					{
						Id = x.Id,
						Title = x.Comment,
						Label = string.Format("{0} {1} {2}", x.SNo, x.CustomerName, x.CreatedOn.ToString("yyyy-MM-dd")),
						Value = Enum.GetName(typeof(MaintenanceStateEnum), x.State)
					};
					return item;
				}),
				alls.PageIndex,
				alls.TotalPages
			});
		}

		[HttpPost]
		[UserValidator]
		public JsonResult View(Customer customer, int maintenanceId)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var model = new MaintenanceModel();
			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(maintenanceId);
			if (null != maintenance)
			{
				model.Id = maintenance.Id;
				model.PNo = maintenance.PNo;
				model.SNo = maintenance.SNo;
				model.PlaceId = maintenance.PlaceId;
				model.PlaceName = maintenance.PlaceName;
				model.CategoryId = maintenance.CategoryId;
				model.CategoryName = maintenance.CategoryName;
				model.InspectionPlanId = maintenance.InspectionPlanId;
				model.Comment = maintenance.Comment;
				model.IsAssign = maintenance.IsAssign;
				model.AssignComment = maintenance.AssignComment;
				model.IsExternal = maintenance.IsExternal;
				model.Total = maintenance.Total;
				model.ResponsibleDepartmentId = maintenance.ResponsibleDepartmentId;
				model.ResponsibleDepartmentName = maintenance.ResponsibleDepartmentName;
				model.ResponsibleTeamId = maintenance.ResponsibleTeamId;
				model.ResponsibleTeamName = maintenance.ResponsibleTeamName;
				model.ResponsiblePersonId = maintenance.ResponsiblePersonId;
				model.ResponsiblePersonName = maintenance.ResponsiblePersonName;
				model.MaintenancePersonNames = maintenance.MaintenancePersonNames;
				model.MaintenanceComment = maintenance.MaintenanceComment;
				model.MaintenanceOn = maintenance.MaintenanceOn.HasValue ? maintenance.MaintenanceOn.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
				model.Star = maintenance.Star;
				model.Evaluation = maintenance.Evaluation;
				model.EvaluationOn = maintenance.EvaluationOn.HasValue ? maintenance.EvaluationOn.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
				model.State = maintenance.State;
				model.StateName = Enum.GetName(typeof(InspectionStateEnum), maintenance.State);
				model.CustomerId = maintenance.Id;
				model.CustomerName = maintenance.CustomerName;
				model.DepartmentId = maintenance.DepartmentId;
				model.DepartmentName = maintenance.DepartmentName;
				model.IsPause = maintenance.IsPause;
				model.CreatedOn = maintenance.CreatedOn.ToString("yyyy-MM-dd HH:mm:ss");
				model.Hours = maintenance.Minutes;
				model.HoursString = GetHoursString(model.Hours);
				var pictures = maintenance.GetAttribute<string>("Pictures");
				if (!string.IsNullOrEmpty(pictures))
				{
					var pictureIds = pictures
						.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
						.Select(x => Convert.ToInt32(x))
						.ToArray();
					foreach (var p in pictureIds)
					{
						model.Pictures.Add(_pictureService.GetPictureUrl(p));
					}
				}
				if (customer.IsResponsibleLeader() && maintenance.State == (int)MaintenanceStateEnum.待指派)
				{
					model.CanAssign = true;
					// 维修部门
					var departs = _departmentService.GetAllDepartments(pid: 0, showHidden: false, isMaintenance: true).ToList();
					if (departs.Any())
					{
						foreach (var t in departs)
						{
							model.AvailableDeparts.Add(new SelectItemModel { Text = t.Name, Id = t.Id });
						}
					}
				}
				// 部门负责人可以确认、分配自己部门的维修任务
				if (customer.IsDepartmentManager() && maintenance.ResponsibleDepartmentId == customer.DepartmentId)
				{
					if (maintenance.State == (int)MaintenanceStateEnum.待确认)
					{
						model.CanConfirm = true;
					}
					if (maintenance.State == (int)MaintenanceStateEnum.待分配)
					{
						model.CanAllocate = true;
					}
					// 维修班组
					var teams = _departmentService.GetAllDepartments(pid: maintenance.ResponsibleDepartmentId, showHidden: false, isMaintenance: true).ToList();
					if (teams.Any())
					{
						foreach (var t in teams)
						{
							model.AvailableTeams.Add(new SelectItemModel { Text = t.Name, Id = t.Id });
						}
					}
					// 维修人员
					var users = _customerService.GetAllCustomers(
						customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
						departId: maintenance.ResponsibleDepartmentId,
						showHidden: false).ToList();
					if (users.Any())
					{
						foreach (var u in users)
						{
							model.AvailableUsers.Add(new SelectItemModel { Text = u.TrueName, Id = u.Id, PId = u.TeamId });
						}
					}
				}
				if (customer.IsRepairman() && maintenance.State == (int)MaintenanceStateEnum.待维修)
				{
					if (maintenance.ResponsibleTeamId > 0 && (maintenance.ResponsibleTeamId == customer.TeamId || maintenance.ResponsibleTeamId == customer.DepartmentId))
					{
						if (maintenance.ResponsiblePersonId == 0 || maintenance.ResponsiblePersonId == customer.Id)
							model.CanComplete = true;
					}
				}
				if (maintenance.State == (int)MaintenanceStateEnum.待评价 && maintenance.CustomerId == customer.Id)
				{
					model.CanComment = true;
				}
				var comments = _xJMaintenanceCommentService.GetAllMaintenanceComments(maintenanceId: maintenance.Id).ToList();
				if (comments.Any())
				{
					foreach (var exchange in comments)
					{
						var urls = new List<string>();
						var videoUrls = new List<string>();
						var exchangesPictures = exchange.GetAttribute<string>("Pictures");
						if (!string.IsNullOrEmpty(exchangesPictures))
						{
							var pictureIds = exchangesPictures
								.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
								.Select(x => Convert.ToInt32(x))
								.ToArray();
							foreach (var p in pictureIds)
							{
								urls.Add(_pictureService.GetPictureUrl(p));
							}
						}
						string videos = exchange.GetAttribute<string>("Videos");
						if (!string.IsNullOrEmpty(videos))
						{
							var videoIds = videos
								.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
								.Select(x => Convert.ToInt32(x))
								.ToArray();
							foreach (var vid in videoIds)
							{
								videoUrls.Add(_filesService.GetFileUrl(vid));
							}
						}
						model.Comments.Add(new MaintenanceCommentViewModel
						{
							Id = exchange.Id,
							Title = exchange.Star > 0 ? string.Format("{0} +{1}分", exchange.Comment, exchange.Star) : exchange.Comment,
							Label = string.Format("{0} {1} {2}", _customerService.GetNameById(exchange.CustomerId), Enum.GetName(typeof(MaintenanceCommentTypeEnum), exchange.TypeId), exchange.CreatedOn.ToString("yyyy-MM-dd HH:mm")),
							Pictures = urls,
							Videos = videoUrls,
						});
					}
				}
				var stockOuts = _xJEquipmentStockOutService.GetAllStockOuts(maintenanceId: maintenance.Id);
				if (stockOuts.Any())
				{
					foreach (var x in stockOuts)
					{
						x.StateName = Enum.GetName(typeof(StockOutStateEnum), x.State);
						x.CreatedOnString = x.CreatedOn.ToString("yyyy-MM-dd HH:mm:ss");
						model.StockOuts.Add(x);
					}
				}

				var categorys = _xJEquipmentCategoryService.GetAllXJEquipmentCategorys().Where(m => !m.IsConsumables);
				var places = _xjPlaceService.GetAllXJPlaces();
				if (maintenance.InspectionPlanId > 0)
				{
					var plan = _xJInspectionPlanService.GetXJInspectionPlanById(maintenance.InspectionPlanId);
					if (null == plan)
						return Json(new { result = false, msg = "巡检计划无效" });

					switch (plan.AimId)
					{
						case (int)AimTypeEnum.设备分类:
							var cs = plan.Categorys.Where(m => !m.Deleted && m.Published);
							if (cs.Any())
							{
								foreach (var c in cs)
								{
									model.AvailableCategories.Add(new SelectItemModel { Id = c.Id, Text = c.Name });
									foreach (var item in categorys.Where(m => m.PId == c.Id))
									{
										model.AvailableCategories.Add(new SelectItemModel { Id = item.Id, Text = item.Name, PId = item.PId });
										foreach (var p in item.Places)
										{
											if (!model.AvailablePlaces.Any(m => m.Id == p.Id))
											{
												model.AvailablePlaces.Add(new SelectItemModel { Id = p.Id, Text = p.Name });
											}
										}
									}
								}
							}
							break;
						case (int)AimTypeEnum.巡检点:
							var ps = plan.Places.Where(m => !m.Deleted && m.Published);
							if (ps.Any())
							{
								foreach (var p in ps)
								{
									model.AvailablePlaces.Add(new SelectItemModel { Id = p.Id, Text = p.Name });
									var ccs = categorys.Where(m => m.Places.Any(c => c.Id == p.Id));
									if (ccs.Any())
									{
										foreach (var c in ccs)
										{
											if (!model.AvailableCategories.Any(m => m.Id == c.Id))
											{
												model.AvailableCategories.Add(new SelectItemModel { Id = c.Id, Text = c.Name, PId = c.PId });
											}
										}
									}
								}
							}
							break;
						default:
							break;
					}
				}
				else
				{
					model.AvailablePlaces = places.Select(x => { return new SelectItemModel { Id = x.Id, Text = x.Name }; }).ToList();
					model.AvailableCategories = categorys.Select(x => { return new SelectItemModel { Id = x.Id, Text = x.Name, PId = x.PId }; }).ToList();
				}
			}
			return Json(new { resut = true, model });
		}

		/// <summary>
		/// 巡检时报修
		/// </summary>
		/// <param name="customer"></param>
		/// <param name="planId"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Create(Customer customer, int planId = 0)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var model = new MaintenanceModel
			{
				InspectionPlanId = planId,
				SNo = _xJMaintenanceService.GenerateNo(),
				State = (int)MaintenanceStateEnum.保存,
				CustomerId = customer.Id,
				CustomerName = customer.TrueName,
				DepartmentId = customer.DepartmentId,
				DepartmentName = customer.TrueName,
				CreatedOn = DateTime.Now.ToString()
			};

			var categorys = _xJEquipmentCategoryService.GetAllXJEquipmentCategorys().Where(m => !m.IsConsumables);
			var places = _xjPlaceService.GetAllXJPlaces();
			if (planId > 0)
			{
				var plan = _xJInspectionPlanService.GetXJInspectionPlanById(planId);
				if (null == plan)
					return Json(new { result = false, msg = "巡检计划无效" });
				switch (plan.AimId)
				{
					case (int)AimTypeEnum.设备分类:
						var cs = plan.Categorys.Where(m => !m.Deleted && m.Published);
						if (cs.Any())
						{
							foreach (var c in cs)
							{
								model.AvailableCategories.Add(new SelectItemModel { Id = c.Id, Text = c.Name });
								foreach (var item in categorys.Where(m => m.PId == c.Id))
								{
									model.AvailableCategories.Add(new SelectItemModel { Id = item.Id, Text = item.Name, PId = item.PId });
									foreach (var p in item.Places)
									{
										if (!model.AvailablePlaces.Any(m => m.Id == p.Id))
										{
											model.AvailablePlaces.Add(new SelectItemModel { Id = p.Id, Text = p.Name });
										}
									}
								}
							}
						}
						break;
					case (int)AimTypeEnum.巡检点:
						var ps = plan.Places.Where(m => !m.Deleted && m.Published);
						if (ps.Any())
						{
							foreach (var p in ps)
							{
								model.AvailablePlaces.Add(new SelectItemModel { Id = p.Id, Text = p.Name });
								var ccs = categorys.Where(m => m.Places.Any(c => c.Id == p.Id));
								if (ccs.Any())
								{
									foreach (var c in ccs)
									{
										if (!model.AvailableCategories.Any(m => m.Id == c.Id))
										{
											model.AvailableCategories.Add(new SelectItemModel { Id = c.Id, Text = c.Name, PId = c.PId });
										}
									}
								}
							}
						}
						break;
					default:
						break;
				}
			}
			else
			{
				model.AvailablePlaces = places.Select(x => { return new SelectItemModel { Id = x.Id, Text = x.Name }; }).ToList();
				model.AvailableCategories = categorys.Select(x => { return new SelectItemModel { Id = x.Id, Text = x.Name, PId = x.PId }; }).ToList();
			}
			if (model.AvailablePlaces.Count() == 1)
			{
				var place = model.AvailablePlaces[0];
				if (null != place)
				{
					model.PlaceId = place.Id;
					model.PlaceName = place.Text;
				}
			}
			if (model.AvailableCategories.Count() == 1)
			{
				var category = model.AvailableCategories[0];
				if (null != category)
				{
					model.CategoryId = category.Id;
					model.CategoryName = category.Text;
				}
			}

			return Json(new { resut = true, model });
		}

		/// <summary>
		/// 常规报修
		/// 直接文字说明、图片，具体设备由后续人员指定
		/// </summary>
		/// <param name="customer"></param>
		/// <param name="planId"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Add(Customer customer)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var model = new MaintenanceModel
			{
				SNo = _xJMaintenanceService.GenerateNo(),
				State = (int)MaintenanceStateEnum.保存,
				CustomerId = customer.Id,
				CustomerName = customer.TrueName,
				DepartmentId = customer.DepartmentId,
				DepartmentName = customer.TrueName,
				CreatedOn = DateTime.Now.ToString()
			};

			return Json(new { resut = true, model });
		}

		/// <summary>
		/// 维修申请
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Save(Customer customer, MaintenanceModel model)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var maintenance = new XJMaintenance
			{
				SNo = _xJMaintenanceService.GenerateNo(),
				InspectionPlanId = model.InspectionPlanId,
				CategoryId = model.CategoryId,
				CategoryName = model.CategoryName,
				PlaceId = model.PlaceId,
				PlaceName = model.PlaceName,
				Comment = model.Comment,
				State = (int)MaintenanceStateEnum.待指派,
				CustomerId = customer.Id,
				CustomerName = customer.TrueName,
				DepartmentId = customer.DepartmentId,
				DepartmentName = customer.DepartmentName,
				CreatedOn = DateTime.Now
			};
			if (model.InspectionPlanId > 0)
			{
				var plan = _xJInspectionPlanService.GetXJInspectionPlanById(model.InspectionPlanId);
				if (plan == null)
					return Json(new { result = false, msg = "巡检计划无效" });
				if (plan.Deleted || !plan.Published)
					return Json(new { result = false, msg = "巡检计划未启用" });

				maintenance.PNo = plan.PNo;
				if (plan.MaintenanceTeamId > 0)
				{
					var team = _departmentService.GetDepartmentById(plan.MaintenanceTeamId);
					if (team != null)
					{
						// 是班组-->待维修
						if (team.PId > 0)
						{
							var depart = _departmentService.GetDepartmentById(team.PId);
							if (depart != null)
							{
								maintenance.ResponsibleDepartmentId = depart.Id;
								maintenance.ResponsibleDepartmentName = depart.Name;
							}
							maintenance.ResponsibleTeamId = team.Id;
							maintenance.ResponsibleTeamName = team.Name;
							maintenance.State = (int)MaintenanceStateEnum.待维修;
						}
						// 是部门-->待确认
						else
						{
							maintenance.ResponsibleDepartmentId = team.Id;
							maintenance.ResponsibleDepartmentName = team.Name;
							maintenance.State = (int)MaintenanceStateEnum.待确认;
						}
					}
				}

				if (plan.MaintenancePersonId > 0)
				{
					// 是维修人-->待维修
					var person = _customerService.GetCustomerById(plan.MaintenancePersonId);
					if (null != person && person.IsRepairman())
					{
						maintenance.ResponsiblePersonId = person.Id;
						maintenance.ResponsiblePersonName = person.TrueName;
						// 维修人
						_xJMaintenanceCustomersService.InsertXJMaintenanceCustomers(new XJMaintenanceCustomers { MaintenanceId = maintenance.Id, CustomerId = person.Id, CustomerName = person.TrueName });
					}
				}

				// 生成漏检记录
				_xJInspectionPlanService.AddLoss(customer, plan);
			}
			_xJMaintenanceService.InsertXJMaintenance(maintenance);

			if (!string.IsNullOrEmpty(model.SelectedPictureIds))
			{
				_genericAttributeService.SaveAttribute(maintenance, "Pictures", model.SelectedPictureIds);
			}

			var comment = new XJMaintenanceComment
			{
				MaintenanceId = maintenance.Id,
				TypeId = (int)MaintenanceCommentTypeEnum.维修申请,
				Comment = model.Comment,
				CustomerId = model.CustomerId,
				CreatedOn = DateTime.Now,
			};
			_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

			return Json(new { result = true, msg = "报修成功", id = maintenance.Id });
		}

		[HttpPost]
		[UserValidator]
		public JsonResult SaveAdd(Customer customer, MaintenanceModel model)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var maintenance = new XJMaintenance
			{
				SNo = _xJMaintenanceService.GenerateNo(),
				CategoryId = model.CategoryId,
				CategoryName = model.CategoryName,
				PlaceId = model.PlaceId,
				PlaceName = model.PlaceName,
				Comment = model.Comment,
				State = (int)MaintenanceStateEnum.待分配,
				CustomerId = customer.Id,
				CustomerName = customer.TrueName,
				DepartmentId = customer.DepartmentId,
				DepartmentName = customer.DepartmentName,
				CreatedOn = DateTime.Now
			};
			_xJMaintenanceService.InsertXJMaintenance(maintenance);

			if (!string.IsNullOrEmpty(model.SelectedPictureIds))
			{
				_genericAttributeService.SaveAttribute(maintenance, "Pictures", model.SelectedPictureIds);
			}

			var comment = new XJMaintenanceComment
			{
				MaintenanceId = maintenance.Id,
				TypeId = (int)MaintenanceCommentTypeEnum.维修申请,
				Comment = model.Comment,
				CustomerId = model.CustomerId,
				CreatedOn = DateTime.Now,
			};
			_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

			return Json(new { result = true, msg = "报修成功", id = maintenance.Id });
		}

		/// <summary>
		/// 部门负责人确认维修任务或申请上级指派
		/// </summary>
		/// <param name="customer"></param>
		/// <param name="maintenanceId"></param>
		/// <param name="responsibleTeamId"></param>
		/// <param name="maintenancePersonIds"></param>
		/// <param name="content"></param>
		/// <param name="pass"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Confirm(Customer customer, int maintenanceId, int responsibleTeamId = 0, int[] maintenancePersonIds = null, string content = "", bool pass = false)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			if (!string.IsNullOrEmpty(content) && content.Length > 50)
				return Json(new { result = false, msg = "备注不能大于50字符" });

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(maintenanceId);
			if (maintenance == null || maintenance.Deleted)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.State != (int)MaintenanceStateEnum.待确认)
				return Json(new { result = false, msg = "无需确认" });

			if (pass)
			{
				if (responsibleTeamId == 0)
					responsibleTeamId = maintenance.ResponsibleDepartmentId;

				var depart = _departmentService.GetDepartmentById(responsibleTeamId);
				if (null != depart)
				{
					var users = _customerService.GetAllCustomers(
							customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
							teamId: depart.Id
						);

					var maintenancePersons = _xJMaintenanceCustomersService.GetMaintenanceCustomerss(maintenance.Id);
					if (maintenancePersons.Any())
					{
						// 清除责任人
						maintenance.ResponsiblePersonId = 0;
						maintenance.ResponsiblePersonName = null;
						foreach (var item in maintenancePersons)
						{
							_xJMaintenanceCustomersService.DeleteXJMaintenanceCustomers(item);
						}
					}

					string maintenancePersonNames = "";
					var names = new List<string>();
					if (maintenancePersonIds != null && maintenancePersonIds.Any())
					{
						foreach (var id in maintenancePersonIds)
						{
							var u = users.FirstOrDefault(m => m.Id == id);
							if (null != u)
							{
								// 第一个为责任人
								if (maintenance.ResponsiblePersonId == 0)
								{
									maintenance.ResponsiblePersonId = u.Id;
									maintenance.ResponsiblePersonName = u.TrueName;
								}
								names.Add(u.TrueName);
								_xJMaintenanceCustomersService.InsertXJMaintenanceCustomers(new XJMaintenanceCustomers
								{
									MaintenanceId = maintenance.Id,
									CustomerId = u.Id,
									CustomerName = u.TrueName
								});
							}
						}
						maintenancePersonNames = string.Join(",", names);
					}

					maintenance.ResponsibleTeamId = depart.Id;
					maintenance.ResponsibleTeamName = depart.Name;
					maintenance.MaintenancePersonNames = CommonHelper.EnsureMaximumLength(maintenancePersonNames, 50, "...");
					maintenance.State = (int)MaintenanceStateEnum.待维修;
					_xJMaintenanceService.UpdateXJMaintenance(maintenance);

					// 分配时新增维修时间表，截止时计算工时
					_xJMaintenanceScheduleService.NewSchedule(new XJMaintenanceSchedule
					{
						MaintenanceId = maintenance.Id,
						StartOn = DateTime.Now,
						StartCustomer = customer.TrueName,
					});

					var comment = new XJMaintenanceComment
					{
						MaintenanceId = maintenance.Id,
						TypeId = (int)MaintenanceCommentTypeEnum.维修分配,
						Comment = string.Format("分配-->{0}{1}", depart.Name, maintenancePersonNames),
						CustomerId = customer.Id,
						CreatedOn = DateTime.Now,
					};
					_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);
				}
			}
			else
			{
				maintenance.ResponsibleDepartmentId = 0;
				maintenance.ResponsibleDepartmentName = null;
				maintenance.ResponsibleTeamId = 0;
				maintenance.ResponsibleTeamName = null;
				maintenance.ResponsiblePersonId = 0;
				maintenance.ResponsiblePersonName = null;
				maintenance.State = (int)MaintenanceStateEnum.待指派;
				_xJMaintenanceService.UpdateXJMaintenance(maintenance);

				var comment = new XJMaintenanceComment
				{
					MaintenanceId = maintenance.Id,
					TypeId = (int)MaintenanceCommentTypeEnum.申请指派,
					Comment = string.Format("申请指派-->{0}", content),
					CustomerId = customer.Id,
					CreatedOn = DateTime.Now,
				};
				_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);
			}
			return Json(new { result = true, msg = "确认成功" });
		}

		/// <summary>
		/// 分管领导指派
		/// </summary>
		/// <param name="customer"></param>
		/// <param name="maintenanceId"></param>
		/// <param name="responsibleTeamId"></param>
		/// <param name="maintenancePersonIds"></param>
		/// <param name="content"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Assign(Customer customer, int maintenanceId, int responsibleDepartmentId, string content = "")
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			if (!string.IsNullOrEmpty(content) && content.Length > 50)
				return Json(new { result = false, msg = "备注不能大于50字符" });

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(maintenanceId);
			if (maintenance == null || maintenance.Deleted)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.State != (int)MaintenanceStateEnum.待指派)
				return Json(new { result = false, msg = "无需指派" });
			var depart = _departmentService.GetDepartmentById(responsibleDepartmentId);
			if (null != depart)
			{

				maintenance.ResponsibleDepartmentId = depart.Id;
				maintenance.ResponsibleDepartmentName = depart.Name;
				maintenance.IsAssign = true;
				maintenance.AssignComment = content;
				maintenance.State = (int)MaintenanceStateEnum.待分配;
				_xJMaintenanceService.UpdateXJMaintenance(maintenance);

				var comment = new XJMaintenanceComment
				{
					MaintenanceId = maintenance.Id,
					TypeId = (int)MaintenanceCommentTypeEnum.维修指派,
					Comment = string.Format("指派-->{0}", depart.Name),
					CustomerId = customer.Id,
					CreatedOn = DateTime.Now,
				};
				_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

				// 所有的指派都必须经过部门负责人才能变更为待维修
				//// 如果选中的部门没有下级维修班组，默认当前部门为维修班组
				//if (!_departmentService.GetAllDepartments(pid:depart.Id,showHidden:false,isMaintenance:true).Any())
				//{
				//	//ErrorNotification("指定的部门没有维修班组");
				//	maintenance.ResponsibleTeamId = depart.Id;
				//	maintenance.ResponsibleTeamName = depart.Name;
				//	maintenance.State = (int)MaintenanceStateEnum.待维修;
				//}
			}

			return Json(new { result = true, msg = "指派成功" });
		}

		/// <summary>
		/// 部门负责人分配维修任务
		/// </summary>
		/// <param name="customer"></param>
		/// <param name="maintenanceId"></param>
		/// <param name="responsibleTeamId"></param>
		/// <param name="maintenancePersonIds"></param>
		/// <param name="content"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Allocate(Customer customer, int maintenanceId, int responsibleTeamId, int[] maintenancePersonIds = null, string content = "")
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			if (!string.IsNullOrEmpty(content) && content.Length > 50)
				return Json(new { result = false, msg = "备注不能大于50字符" });

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(maintenanceId);
			if (maintenance == null || maintenance.Deleted)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.State != (int)MaintenanceStateEnum.待分配)
				return Json(new { result = false, msg = "无需分配" });

			if (responsibleTeamId == 0)
				responsibleTeamId = maintenance.ResponsibleDepartmentId;

			var depart = _departmentService.GetDepartmentById(responsibleTeamId);
			if (null != depart)
			{
				var users = _customerService.GetAllCustomers(
						customerRoleIds: new int[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id },
						teamId: depart.Id
					);

				var maintenancePersons = _xJMaintenanceCustomersService.GetMaintenanceCustomerss(maintenance.Id);
				if (maintenancePersons.Any())
				{
					// 清除责任人
					maintenance.ResponsiblePersonId = 0;
					maintenance.ResponsiblePersonName = null;
					foreach (var item in maintenancePersons)
					{
						_xJMaintenanceCustomersService.DeleteXJMaintenanceCustomers(item);
					}
				}

				string maintenancePersonNames = "";
				var names = new List<string>();
				if (maintenancePersonIds != null && maintenancePersonIds.Any())
				{
					foreach (var id in maintenancePersonIds)
					{
						var u = users.FirstOrDefault(m => m.Id == id);
						if (null != u)
						{
							// 第一个为责任人
							if (maintenance.ResponsiblePersonId == 0)
							{
								maintenance.ResponsiblePersonId = u.Id;
								maintenance.ResponsiblePersonName = u.TrueName;
							}
							names.Add(u.TrueName);
							_xJMaintenanceCustomersService.InsertXJMaintenanceCustomers(new XJMaintenanceCustomers
							{
								MaintenanceId = maintenance.Id,
								CustomerId = u.Id,
								CustomerName = u.TrueName
							});
						}
					}
					maintenancePersonNames = string.Join(",", names);
				}

				maintenance.ResponsibleTeamId = depart.Id;
				maintenance.ResponsibleTeamName = depart.Name;
				maintenance.MaintenancePersonNames = CommonHelper.EnsureMaximumLength(maintenancePersonNames, 50, "...");
				maintenance.State = (int)MaintenanceStateEnum.待维修;
				_xJMaintenanceService.UpdateXJMaintenance(maintenance);

				// 分配时新增维修时间表，截止时计算工时
				_xJMaintenanceScheduleService.NewSchedule(new XJMaintenanceSchedule
				{
					MaintenanceId = maintenance.Id,
					StartOn = DateTime.Now,
					StartCustomer = customer.TrueName,
				});

				var comment = new XJMaintenanceComment
				{
					MaintenanceId = maintenance.Id,
					TypeId = (int)MaintenanceCommentTypeEnum.维修分配,
					Comment = string.Format("分配-->{0}{1}", depart.Name, maintenancePersonNames),
					CustomerId = customer.Id,
					CreatedOn = DateTime.Now,
				};
				_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);
			}

			return Json(new { result = true, msg = "分配成功" });
		}

		/// <summary>
		/// 暂停/启动
		/// </summary>
		/// <param name="id"></param>
		/// <param name="isStart">启动</param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public virtual ActionResult Pause(Customer customer, int maintenanceId, bool isStart = false, string content = "")
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(maintenanceId);
			if (maintenance == null)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.State != (int)MaintenanceStateEnum.待维修)
				return Json(new { result = false, msg = "不是待维修状态" });

			var result = _xJMaintenanceService.Pause(xJMaintenanceId: maintenanceId, customer: customer, isStart: isStart, comment: content);
			if (!result.Result)
			{
				return Json(new { result = false, msg = result.Msg });
			}

			var comment = new XJMaintenanceComment
			{
				MaintenanceId = maintenance.Id,
				TypeId = isStart ? (int)MaintenanceCommentTypeEnum.维修启动 : (int)MaintenanceCommentTypeEnum.维修暂停,
				Comment = string.Format("{0} {1}", isStart ? "启动" : "暂停", content),
				CustomerId = customer.Id,
				CreatedOn = DateTime.Now,
			};
			_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);

			return Json(new { result = true });
		}

		/// <summary>
		/// 完工汇报
		/// </summary>
		/// <param name="customerId"></param>
		/// <param name="maintenanceId"></param>
		/// <param name="teamId"></param>
		/// <param name="personId"></param>
		/// <param name="content"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Complete(Customer customer, int maintenanceId, List<XJMaintenanceDetail> details = null, string content = "", string selectedPictureIds = null, bool isExternal = false, decimal total = 0)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			if (customer.TeamId <= 0)
				return Json(new { result = false, msg = "非班组人员不能操作" });

			if (!string.IsNullOrEmpty(content) && content.Length > 50)
				return Json(new { result = false, msg = "补充说明为1~50字" });

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(maintenanceId);
			if (maintenance == null || maintenance.Deleted)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.IsPause)
				return Json(new { result = false, msg = "报修暂停" });

			if (null != details && details.Any())
			{
				foreach (var detail in details)
				{
					var stock = _xJEquipmentStockService.GetXJEquipmentStockById(detail.EquipmentStockId);
					if (null == stock)
						return Json(new { result = false, msg = "请选择设施设备" });
					if (stock.State == (int)StockStateEnum.报废)
						return Json(new { result = false, msg = "选择的设施设备已报废" });

					_xJMaintenanceDetailService.InsertXJMaintenanceDetail(new XJMaintenanceDetail
					{
						MaintenanceId = maintenance.Id,
						EquipmentStockId = detail.EquipmentStockId,
						EquipmentId = detail.EquipmentId,
						Name = detail.Name,
						Manufacturer = detail.Manufacturer,
						Specification = detail.Specification,
						Location = detail.Location,
					});
				}
			}
			var outs = _xJEquipmentStockOutService.GetAllStockOuts(maintenanceId: maintenance.Id, state: (int)StockOutStateEnum.待审核);
			if (outs.Any())
				return Json(new { result = false, msg = "领用申请未完结" });

			var result = _xJMaintenanceService.Complete(xJMaintenanceId: maintenanceId, customer: customer, isExternal: isExternal, total: total);
			if (!result.Result)
			{
				return Json(new { result = false, msg = result.Msg });
			}

			var comment = new XJMaintenanceComment
			{
				MaintenanceId = maintenance.Id,
				TypeId = (int)MaintenanceCommentTypeEnum.完工汇报,
				Comment = content,
				CustomerId = customer.Id,
				CreatedOn = DateTime.Now,
			};
			_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);
			if (!string.IsNullOrEmpty(selectedPictureIds))
			{
				_genericAttributeService.SaveAttribute(comment, "Pictures", selectedPictureIds);
			}

			return Json(new { result = true, msg = "汇报成功" });
		}

		/// <summary>
		/// 维修评价
		/// </summary>
		/// <param name="customerId"></param>
		/// <param name="maintenanceId"></param>
		/// <param name="star"></param>
		/// <param name="content"></param>
		/// <param name="selectedPictureIds"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Comment(Customer customer, int maintenanceId, int star = 0, string content = "", string selectedPictureIds = null)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			if (string.IsNullOrEmpty(content) || content.Length > 50)
				return Json(new { result = false, msg = "补充说明为1~50字" });
			if (star < 1 || star > 100)
				return Json(new { result = false, msg = "评分无效" });

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(maintenanceId);
			if (maintenance == null || maintenance.Deleted)
				return Json(new { result = false, msg = "报修记录无效" });

			if (maintenance.State != (int)MaintenanceStateEnum.待评价)
				return Json(new { result = false, msg = "未维修完成，不能评价" });

			var comment = new XJMaintenanceComment
			{
				MaintenanceId = maintenance.Id,
				TypeId = (int)MaintenanceCommentTypeEnum.维修评价,
				Comment = content,
				Star = star,
				CustomerId = customer.Id,
				CreatedOn = DateTime.Now,
			};
			_xJMaintenanceCommentService.InsertXJMaintenanceComment(comment);
			if (!string.IsNullOrEmpty(selectedPictureIds))
			{
				_genericAttributeService.SaveAttribute(comment, "Pictures", selectedPictureIds);
			}

			maintenance.Star = star;
			maintenance.Evaluation = content;
			maintenance.EvaluationOn = DateTime.Now;
			maintenance.State = (int)MaintenanceStateEnum.已完工;
			_xJMaintenanceService.UpdateXJMaintenance(maintenance);
			return Json(new { result = true, msg = "评价成功" });
		}

		/// <summary>
		/// 维修申请提醒维修部负责人（TeamId班组为0）
		/// </summary>
		/// <param name="id"></param>
		/// <param name="templateId"></param>
		/// <returns></returns>
		public async Task<JsonResult> SubscribeMessage(int id, string templateId = "nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k")
		{
			await AccessTokenContainer.RegisterAsync(appId, appSecret);

			var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
			if (null == maintenance || maintenance.Deleted)
				return Json(new { success = false, msg = "维修申请无效" });

			string page = string.Format("pages/maintenance/detail?id={0}", maintenance.Id);
			string thing1 = "";
			var users = new List<Customer>();
			switch (maintenance.State)
			{
				case (int)MaintenanceStateEnum.待确认:
					thing1 = string.Format("新的维修任务待确认");
					users = _customerService.GetAllCustomers(
						customerRoleId: _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.DepartmentManager).Id,
						departId: maintenance.ResponsibleDepartmentId
						).ToList();
					break;
				case (int)MaintenanceStateEnum.待指派:
					thing1 = string.Format("新的维修任务待指派");
					users = _customerService.GetAllCustomers(
						customerRoleId: _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.ResponsibleLeader).Id,
						departId: maintenance.ResponsibleDepartmentId
						).ToList();
					break;
				case (int)MaintenanceStateEnum.待分配:
					thing1 = string.Format("新的维修任务待分配");
					users = _customerService.GetAllCustomers(
						customerRoleId: _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.DepartmentManager).Id,
						departId: maintenance.ResponsibleDepartmentId
						).ToList();
					break;
				case (int)MaintenanceStateEnum.待维修:
					thing1 = string.Format("新的维修任务待处理");
					if (maintenance.ResponsiblePersonId > 0)
					{
						var repairman = _customerService.GetCustomerById(maintenance.ResponsiblePersonId);
						if (null != repairman)
						{
							users.Add(repairman);
						}
					}
					else
					{
						users = _customerService.GetAllCustomers(
						customerRoleId: _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id,
						teamId: maintenance.ResponsibleTeamId).ToList();
					}
					break;
				case (int)MaintenanceStateEnum.待评价:
					thing1 = string.Format("维修任务已完工，请评价");
					var customer = _customerService.GetCustomerById(maintenance.CustomerId);
					if (null != customer)
					{
						users.Add(customer);
					}
					break;
				default:
					break;
			}
			if (!users.Any())
				return Json(new { success = false, msg = "无通知用户" });

			try
			{
				var templateMessageData = new TemplateMessageData
				{
					["thing1"] = new TemplateMessageDataValue(thing1),
					["date2"] = new TemplateMessageDataValue(maintenance.CreatedOn.ToString("yyyy年MM月dd日 HH:mm"))
				};

				List<string> openIds = new List<string>();
				string msg = string.Empty;
				bool hasFinished = false;

				foreach (var c in users)
				{
					string openId = c.GetAttribute<string>(SystemCustomerAttributeNames.OpenId);
					if (!string.IsNullOrEmpty(openId))
					{
						openIds.Add(openId);
					}
				}
				foreach (var openId in openIds)
				{
					var result = await MessageApi.SendSubscribeAsync(appId, openId, templateId, templateMessageData, page);
					if (result.errcode == ReturnCode.请求成功)
					{
						hasFinished = true;
					}
					else
					{
						msg = "消息发送失败";
						_logger.Error(result.errmsg);
					}
				}
				if (!hasFinished && !string.IsNullOrEmpty(msg))
					return Json(new { success = false, msg });
				else
				{
					return Json(new { success = true, msg = "消息已发送" });
				}
			}
			catch (Exception ex)
			{
				_logger.Error(ex.Message);
				return Json(new { success = false, msg = "消息发送失败" });
			}
		}

		///// <summary>
		///// 任务分配后提醒被分配人员
		///// </summary>
		///// <param name="id"></param>
		///// <param name="templateId"></param>
		///// <returns></returns>
		//public async Task<JsonResult> AlloteMessage(int id, string templateId = "nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k")
		//{
		//	await AccessTokenContainer.RegisterAsync(appId, appSecret);

		//	var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
		//	if (null == maintenance || maintenance.Deleted)
		//		return Json(new { success = false, msg = "维修申请无效" });

		//	try
		//	{
		//		var templateMessageData = new TemplateMessageData
		//		{
		//			["thing1"] = new TemplateMessageDataValue(maintenance.Comment),
		//			["date2"] = new TemplateMessageDataValue(maintenance.CreatedOn.ToString("yyyy年MM月dd日 HH:mm"))
		//		};

		//		string page = string.Format("pages/maintenance/detail?id={0}", maintenance.Id);
		//		List<string> openIds = new List<string>();
		//		string msg = string.Empty;
		//		bool hasFinished = false;

		//		var dCustomers = _customerService.GetAllCustomers(
		//				customerRoleId: _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman).Id,
		//				teamId: maintenance.ResponsibleTeamId
		//			);
		//		if (dCustomers.Any())
		//		{
		//			foreach (var c in dCustomers)
		//			{
		//				string openId = c.GetAttribute<string>(SystemCustomerAttributeNames.OpenId);
		//				if (!string.IsNullOrEmpty(openId))
		//				{
		//					openIds.Add(openId);
		//				}
		//			}
		//		}

		//		foreach (var openId in openIds)
		//		{
		//			var result = await MessageApi.SendSubscribeAsync(appId, openId, templateId, templateMessageData, page);
		//			if (result.errcode == ReturnCode.请求成功)
		//			{
		//				hasFinished = true;
		//			}
		//			else
		//			{
		//				msg = "消息发送失败";
		//				_logger.Error(result.errmsg);
		//			}
		//		}
		//		if (!hasFinished && !string.IsNullOrEmpty(msg))
		//			return Json(new { success = false, msg });
		//		else
		//		{
		//			//message.IsFinished = true;
		//			//_messageService.UpdateMessage(message);
		//			return Json(new { success = true, msg = "消息已发送" });
		//		}
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.Error(ex.Message);
		//		return Json(new { success = false, msg = "消息发送失败" });
		//	}
		//}

		///// <summary>
		///// 完工后提醒申请人员
		///// </summary>
		///// <param name="id"></param>
		///// <param name="templateId"></param>
		///// <returns></returns>
		//public async Task<JsonResult> RemindMessage(int id, string templateId = "nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k")
		//{
		//	await AccessTokenContainer.RegisterAsync(appId, appSecret);

		//	var maintenance = _xJMaintenanceService.GetXJMaintenanceById(id);
		//	if (null == maintenance || maintenance.Deleted)
		//		return Json(new { success = false, msg = "维修申请无效" });

		//	try
		//	{
		//		var templateMessageData = new TemplateMessageData
		//		{
		//			["thing1"] = new TemplateMessageDataValue(maintenance.SNo + "维修完成"),
		//			["date2"] = new TemplateMessageDataValue(maintenance.CreatedOn.ToString("yyyy年MM月dd日 HH:mm"))
		//		};

		//		string page = string.Format("pages/maintenance/detail?id={0}", maintenance.Id);
		//		List<string> openIds = new List<string>();
		//		string msg = string.Empty;
		//		bool hasFinished = false;

		//		var customer = _customerService.GetCustomerById(maintenance.CustomerId);
		//		if (null != customer && !customer.Deleted)
		//		{
		//			string openId = customer.GetAttribute<string>(SystemCustomerAttributeNames.OpenId);
		//			if (!string.IsNullOrEmpty(openId))
		//			{
		//				openIds.Add(openId);
		//			}
		//		}
		//		foreach (var openId in openIds)
		//		{
		//			var result = await MessageApi.SendSubscribeAsync(appId, openId, templateId, templateMessageData, page);
		//			if (result.errcode == ReturnCode.请求成功)
		//			{
		//				hasFinished = true;
		//			}
		//			else
		//			{
		//				msg = "消息发送失败";
		//				_logger.Error(result.errmsg);
		//			}
		//		}
		//		if (!hasFinished && !string.IsNullOrEmpty(msg))
		//			return Json(new { success = false, msg });
		//		else
		//		{
		//			//message.IsFinished = true;
		//			//_messageService.UpdateMessage(message);
		//			return Json(new { success = true, msg = "消息已发送" });
		//		}
		//	}
		//	catch (Exception ex)
		//	{
		//		_logger.Error(ex.Message);
		//		return Json(new { success = false, msg = "消息发送失败" });
		//	}
		//}
	}
}